package com.landmark;

import java.io.FileWriter;
import java.util.Enumeration;
import java.util.Hashtable;
//import javax.lang.model.element.Element;
//import javax.lang.model.util.Elements;
import javax.swing.JTextArea;
import javax.swing.SwingWorker;
//import javax.swing.text.Document;
import org.htmlparser.Node;
//import javax.xml.soap.Node;
import org.htmlparser.Parser;
import org.htmlparser.filters.HasAttributeFilter;
import org.htmlparser.nodes.TagNode;
import org.htmlparser.nodes.TextNode;
import org.htmlparser.util.NodeIterator;
import org.htmlparser.util.NodeList;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

/**
 *
 * @author computer KKM Used to get the Description from the Site www.Blauer.com
 */
public class Blauer extends SwingWorker<Boolean, Boolean> {

    FileWriter fw = null;
    FileWriter fwErrorFile = null;
    int pageNo;
    StringBuffer sb = new StringBuffer();
    Hashtable<String, String> htModelLinks = new Hashtable<String, String>();
    JTextArea txtArea;
    String status = "";

    @Override
    protected Boolean doInBackground() throws Exception {
        start();
        return true;
    }

    @Override
    protected void done() {
        Util.taskCompleteMsg(status);
    }

    /**
     * @param args
     */
    public void start() {
        try {
            String dirName = "./outputs";

            Util.createDirectory(dirName);
            txtArea = Util.createOutputFile("Blauer");
            
            fw = new FileWriter(Util.getHelperBean().getOutputFile());
            fwErrorFile = new FileWriter(Util.getHelperBean().getErrorFile());
            HelperBean helperBean = Util.getHelperBean();

            // Process the main page to get the main category links which are on the left side menu of the page            
            for (pageNo = 1; pageNo <= 20; pageNo++) {
                if (Util.getHelperBean().isTerminateCurrentProcess()) {
                    break;
                }
                String str = "http://www.blauer.com/allproducts/?p=" + pageNo;
                txtArea.setText(str);
                txtArea.paintImmediately(txtArea.getVisibleRect());
                processHomePageLinks(str);
            }
            
            txtArea.append("\nFiles are located at : \n" + helperBean.getOutputFile().getAbsolutePath() + "\n" + helperBean.getOutputFile().getAbsolutePath() + "\n");
            txtArea.append("Total products : " + htModelLinks.size() + "\n");
            txtArea.paintImmediately(txtArea.getVisibleRect());

            Enumeration mainCatEnum = htModelLinks.keys();
            while (mainCatEnum.hasMoreElements()) {
                if (Util.getHelperBean().isTerminateCurrentProcess()) {
                    break;
                }
                sb = new StringBuffer();
                String key = (String) mainCatEnum.nextElement();

                txtArea.append("Processing page: " + key + "\n");
                txtArea.paintImmediately(txtArea.getVisibleRect());

                fw.write("\n");
                //processModel("http://www.blauer.com/zip-front-breakaway-safety-vest-342f.html");
                processModel(htModelLinks.get(key));
                String str = sb.toString();
                str = str.replaceAll("\r", "").replaceAll("\n", "").replaceAll("   ", "").replaceAll("<li>", "<li>").replaceAll("<div>", "").replaceAll("<LMITLINE>", "").replaceAll("<titlespan>", "\n");
                fw.write(str);
                fw.flush();
            }
            if (fw != null) {
                fw.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (fw != null) {
                    fw.close();
                }
            } catch (Exception e1) {
                // TODO: handle exception
            }
        }
        status = "Done processing.";
        if (Util.getHelperBean().isTerminateCurrentProcess()) {
            status = "Process Terminated";
        }
        txtArea.append("\n" + status);
    }

    private boolean processModel(String aUrl) {
        boolean status = false;
        try {
            System.out.println("Process model : " + aUrl);
            Parser parser = Util.getParserFromUrl(aUrl, null);

            // to know which URL/model we have the data for in the final output/file
            fw.write(aUrl + "\n");

            NodeList nl = parser.parse(new HasAttributeFilter("class", "collateral-tabs"));
            //NodeList tableNodes = nl.extractAllNodesThatMatch(new HasAttributeFilter("class", "tab-content"), true);

            for (int i = 0; i < nl.size(); i++) {
                Node targetTableNode = nl.elementAt(i);// retrives the table content where the description starts which we are intersetd in.			
                sb.append("<LMITLINE>");
                iterateTag(targetTableNode);
            }
        } catch (Exception e) {
            try {
                fwErrorFile.write(aUrl + " \n" + e.getMessage() + " \n");
                fwErrorFile.flush();
                e.printStackTrace();
            } catch (Exception e1) {
                // TODO: handle exception
            }
        }
        return status;
    }
    boolean isDtTag = false;

    private void iterateTag(Node aNode) throws Exception {
        //try{
        //sb = new StringBuffer();
        if (aNode instanceof TextNode) {
            // downcast to TextNode
            TextNode text = (TextNode) aNode;

            sb.append(text.getText());// manipulating for table data which contains commas in one column
        } else if (aNode instanceof TagNode) {
            // downcast to TagNode
            TagNode tag = (TagNode) aNode;

            if (tag.getRawTagName().equalsIgnoreCase("li")) {
                //System.out.println(tag.getRawTagName());
                sb.append("<li>");
            }

            if (tag.getRawTagName().equalsIgnoreCase("div")) {
                String attrib = tag.getAttribute("class");
                if (attrib != null && attrib.equalsIgnoreCase("text")) {
                    sb.append("<div>");
                }
            }
            if (tag.getRawTagName().equalsIgnoreCase("dt")) {
                String attrib = tag.getAttribute("class");
                if (attrib != null && attrib.equalsIgnoreCase("tab")) {
                    isDtTag = true;
                }
            }
            if (tag.getRawTagName().equalsIgnoreCase("span")) {
                if (isDtTag) {
                    sb.append("<titlespan>");
                    isDtTag = false;
                }
            }
            // process recursively (nodes within nodes) via getChildren()				
            NodeList nl = tag.getChildren();
            if (null != nl) {
                try {
                    for (NodeIterator i = nl.elements(); i.hasMoreNodes();) {
                        iterateTag(i.nextNode());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private void processHomePageLinks(String aUrl) {
        try {
            Document doc = Jsoup.connect(aUrl).get();
            Elements catElements = doc.getElementsByClass("product-image").select("a[href]");
            for (Element element : catElements) {
                //System.out.println(element.attr("abs:href"));
                htModelLinks.put(element.attr("abs:href"), element.attr("abs:href"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
